# main.py
# 作者: [吉他钢琴曲]
# 描述: 该脚本用于将时间戳转换为指定格式的时间字符串，并通过悬浮窗显示转换结果。
# 版本: 1.0
# 日期: [2025-04-08]

import datetime
import logging
import tkinter as tk
from tkinter import messagebox

import pyperclip
from pynput import keyboard

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 时间格式配置
TIME_FORMAT = "%Y-%m-%d %H:%M:%S.%f"

# 悬浮窗列表
floating_windows = []


def convert_timestamp(timestamp):
    """
    将时间戳转换为指定格式的时间字符串
    :param timestamp: 时间戳
    :return: 转换后的时间字符串
    """
    try:
        timestamp = float(timestamp)
        # 处理毫秒级时间戳
        if timestamp > 1e10:
            timestamp /= 1000
        dt = datetime.datetime.fromtimestamp(timestamp)
        formatted_time = dt.strftime(TIME_FORMAT)
        # 保留三位小数
        formatted_time = formatted_time[:-3]
        return formatted_time
    except (ValueError, OSError):
        return None


def on_activate():
    """
    按下快捷键时的处理函数
    """
    try:
        # 读取剪贴板内容
        clipboard_text = pyperclip.paste()
        logging.info(f"从剪贴板读取的内容: {clipboard_text}")
        converted_time = convert_timestamp(clipboard_text)
        if converted_time:
            logging.info(f"转换后的时间: {converted_time}")
            show_floating_window(clipboard_text, converted_time)
        else:
            logging.info("剪贴板内容不是有效的时间戳")
    except Exception as e:
        logging.error(f"处理剪贴板内容时出错: {e}")


def show_floating_window(original_timestamp, converted_time):
    """
    显示悬浮窗
    :param original_timestamp: 原始时间戳
    :param converted_time: 转换后的时间
    """
    try:
        root = tk.Tk()
        root.overrideredirect(True)
        root.attributes("-topmost", True)
        root.attributes("-alpha", 0.8)

        # 悬浮窗内容，去掉边框
        text = f"{original_timestamp}\n{converted_time}"
        label = tk.Label(root, text=text, bg="white", bd=0)
        label.pack(padx=10, pady=5)

        # 绑定双击事件
        label.bind("<Double-1>", lambda event: copy_text_to_clipboard(converted_time))

        # 绑定鼠标拖动事件
        def on_drag_start(event):
            root._drag_start_x = event.x
            root._drag_start_y = event.y

        def on_drag_motion(event):
            x = root.winfo_x() - root._drag_start_x + event.x
            y = root.winfo_y() - root._drag_start_y + event.y
            root.geometry(f"+{x}+{y}")

        label.bind("<ButtonPress-1>", on_drag_start)
        label.bind("<B1-Motion>", on_drag_motion)

        # 监听 Esc 键关闭窗口
        def on_esc_press(event):
            close_window(root)

        root.bind("<Escape>", on_esc_press)

        # 获取鼠标位置并设置悬浮窗位置
        x, y = root.winfo_pointerxy()
        root.geometry(f"+{x}+{y - 50}")

        floating_windows.append(root)
        root.mainloop()
    except Exception as e:
        logging.error(f"显示悬浮窗时出错: {e}")


def close_window(window):
    """
    关闭指定的悬浮窗
    :param window: 要关闭的悬浮窗
    """
    try:
        window.destroy()
        floating_windows.remove(window)
    except Exception as e:
        logging.error(f"关闭悬浮窗时出错: {e}")


def close_all_windows():
    """
    关闭所有悬浮窗
    """
    try:
        for window in floating_windows.copy():
            close_window(window)
    except Exception as e:
        logging.error(f"关闭所有悬浮窗时出错: {e}")


def copy_text_to_clipboard(text):
    """
    将文本复制到剪贴板并提示
    :param text: 要复制的文本
    """
    try:
        pyperclip.copy(text)
        messagebox.showinfo("提示", "已复制到剪贴板")
    except Exception as e:
        logging.error(f"复制文本到剪贴板时出错: {e}")


# 定义快捷键状态
is_win_pressed = False
is_w_pressed = False


def on_press(key):
    global is_win_pressed, is_w_pressed
    try:
        if key in [keyboard.Key.cmd, keyboard.Key.cmd_r]:
            is_win_pressed = True
        elif key == keyboard.KeyCode(char='w'):
            if is_win_pressed:
                is_w_pressed = True
                on_activate()
            elif not is_win_pressed:
                is_w_pressed = True
    except AttributeError:
        pass


def on_release(key):
    global is_win_pressed, is_w_pressed
    try:
        if key in [keyboard.Key.cmd, keyboard.Key.cmd_r]:
            is_win_pressed = False
        elif key == keyboard.KeyCode(char='w'):
            is_w_pressed = False
    except AttributeError:
        pass


# 监听键盘事件
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    logging.info("开始监听快捷键 <win>+<w>")
    listener.join()
